﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace MetaDrive.FluentCode
{
    public sealed class CodeClassInheritanceIterator : IEnumerable<EnvDTE80.CodeClass2>
    {
        private EnvDTE80.CodeClass2 element;

        public CodeClassInheritanceIterator(EnvDTE80.CodeClass2 element)
        {
            if (element == null)
                throw new ArgumentNullException("element");

            this.element = element;
        }

        public IEnumerator<EnvDTE80.CodeClass2> GetEnumerator()
        {
            return Enumerate(element).Select(codeElement => codeElement).GetEnumerator();
        }
        
        private IEnumerable<EnvDTE80.CodeClass2> Enumerate(EnvDTE80.CodeClass2 element)
        {
            if (element != null)
                yield return element;

            foreach (EnvDTE.CodeElement baseElement in element.Bases)
            {
                EnvDTE80.CodeClass2 parentClass = baseElement as EnvDTE80.CodeClass2;
                if (parentClass != null && parentClass.FullName != "System.Object")
                {
                    foreach (var f in Enumerate(parentClass))  
                        yield return f;
                }
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}